<script setup lang="ts">
import {
  delRoleUserAPI,
  getRoleDetailAPI,
  getRoleListAPI,
  getRoleUserAPI,
  getTreeListAPI,
} from "@/apis/system";
import type { Role, RoleData, RoleUser } from "@/types/system";
import { ref } from "vue";

import user from "@/assets/user.svg";
import activeUser from "@/assets/user-active.svg";
import { ElMessage, ElMessageBox, type TreeInstance } from "element-plus";
import type { PageParams } from "@/types/common";
import { useRouter } from "vue-router";

// 1. 获取角色列表
const RoleList = ref<Role[]>([]);
const getRoleList = async () => {
  const res = await getRoleListAPI();
  // console.log(res)
  RoleList.value = res.data;
  const roleId = res.data[0].roleId;
  getRoleDetail(roleId);
};
getRoleList();

// 2. 点击激活交互
const activeIndex = ref(0);
const changeRole = async (idx: number, roleId: number) => {
  // 设置高亮效果
  activeIndex.value = idx;
  getRoleDetail(roleId);

  getRoleUserList(roleId)
};

// 3.获取权限列表-树形
const treeList = ref<RoleData[]>([]);
const getTreeList = async () => {
  const res = await getTreeListAPI();
  // console.log(res)
  treeList.value = res.data;
};
getTreeList();

// 4. 获取角色详情
const perms = ref<number[][]>([]);
const usertotal = ref(0) // 成员数量
// 注意，这里是数组
const treeRefs = ref<TreeInstance[]>([]);
const getRoleDetail = async (roleId: number) => {
  const res = await getRoleDetailAPI(roleId);
  // console.log(res);
  perms.value = res.data.perms;
  usertotal.value = res.data.userTotal; //保存成员数量
  // 切换时，设置树形组件选中
  treeRefs.value.forEach((tree, index) => {
    // 选中节点，setCheckedKeys 优先级高于 default-checked-keys(默认占位)
    tree.setCheckedKeys(perms.value[index]);
  });
};


const activeTabName = ref<'tree'| 'member'>('tree') // 默认打开

// 成员列表
const roleUserList = ref<RoleUser[]>([])
const getRoleUserList =async (roleId:number)=>{
const res = await getRoleUserAPI(roleId)
// console.log(res)
roleUserList.value = res.data.rows
}
// 分页组件
const PageParams =ref<PageParams>({
  page: 1,
  pageSize: 10
})
const total = ref(0)

const router = useRouter()

// 7. 删除角色
const delRole = async (roleId: number) => {
  // 确认弹窗
  ElMessageBox.confirm('是否确认删除当前角色?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 删除角色
    await delRoleUserAPI(roleId)
    // 获取角色列表
    getRoleList()
    // 轻提示
    ElMessage.success('删除成功')
  }).catch(() => { })
}

</script>

<template>
  <div class="role-container">
    <div class="left-wrapper">
      <div
        class="role-item"
        v-for="(item, index) in RoleList"
        :key="item.roleId"
        @click="changeRole(index, item.roleId)"
        :class="{ active: index === activeIndex }"
      >
        <div class="role-info">
          <img :src="index === activeIndex ? activeUser : user" class="icon" />
          {{ item.roleName }}
        </div>

        <div class="more">
          <el-dropdown>
            <span class="el-dropdown-link">
              <img src="@/assets/more.svg" class="icon" />
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="$router.push(`/roleAdd?id=${item.roleId}`)">
                  <el-button @click="" link>编辑角色</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="danger" @click="delRole(item.roleId)" link>删除</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <el-button class="addBtn" size="small" @click="$router.push('/roleAdd')">添加角色</el-button>
    </div>
    <!-- 右侧权限和成员 -->
    <div class="right-wrapper">
      <el-tabs v-model="activeTabName">
        <el-tab-pane label="功能权限" name="tree">  

          <div class="tree-wrapper">
        <!-- 角色权限列表 -->
        <div v-for="(item, index) in treeList" :key="item.id" class="tree-item">
          <div class="tree-title">{{ item.title }}</div>
          <el-tree
            :data="item.children"
            :props="{ label: 'title', disabled: () => true }"
            default-expand-all
            show-checkbox
            :default-checked-keys="perms[index]"
            node-key="id"
            ref="treeRefs"
          />
        </div>
      </div>
        </el-tab-pane>
        <el-tab-pane :label="`成员(${usertotal})`" name="member">
          <div class="user-wrapper">
            <el-table :data="roleUserList">
              <el-table-column type="index" width="250" label="序号" />
              <el-table-column prop="name" label="员工姓名" />
              <el-table-column prop="userName" label="登录账号" />
            </el-table>
          </div>
                <!-- 分页组件 -->
      <div class="page-container">
      <el-pagination 
        layout="total, prev, pager, next, sizes, jumper" 
        :page-sizes="[2, 5, 10, 20, 100]"
        :total="total"
        v-model:page-size="PageParams.pageSize"
        v-model:current-page="PageParams.page"

      />
    </div>
        </el-tab-pane>
      </el-tabs>

    </div>
  </div>
</template>

<style scoped lang="scss">
.role-container {
  display: flex;
  font-size: 14px;
  background-color: #fff;

  .left-wrapper {
    width: 200px;
    border-right: 1px solid #e4e7ec;
    padding: 4px;
    text-align: center;

    .role-item {
      position: relative;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      cursor: pointer;

      &.active {
        background: #edf5ff;
        color: #4770ff;
      }
    }

    .role-info {
      display: flex;
      align-items: center;

      .icon {
        margin-right: 10px;
        width: 20px;
      }
    }

    .more {
      display: flex;
      align-items: center;
      .icon {
        width: 15px;
      }
    }

    .addBtn {
      width: 100%;
      margin-top: 20px;
    }
  }

  .right-wrapper {
    flex: 1;

    .tree-wrapper {
      display: flex;
      justify-content: space-between;

      .tree-item {
        flex: 1;
        border-right: 1px solid #e4e7ec;
        padding: 0px 4px;
        text-align: center;

        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }

    ::v-deep .el-tabs__nav-wrap {
      padding-left: 20px;
    }

    .user-wrapper {
      padding: 20px;
    }
  }
}
</style>
